package com.monkeygroup.mygoplus.view.entrance.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.common.DefinedView.MyAlertDialog;
import com.monkeygroup.mygoplus.common.utils.LocalInfo;
import com.monkeygroup.mygoplus.common.utils.VilidateUtil;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.monkeygroup.mygoplus.user.vo.LoginResultVO;
import com.monkeygroup.mygoplus.user.vo.PersonalNomalInfo;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by cumt on 2017/3/12.
 */

public class SetPasswordFragment  extends Fragment implements View.OnClickListener{

    private View mView;

    private Activity activity;
    //头部
    private TextView txtTitle;
    private ImageView imgBack;

    private EditText etUsername;
    private EditText etPassword;
    private EditText etPwd;
    private TextView uernameTv,passwordTv,tvPwd,btn_pwd_next;

    //提示
    private TextView noticeUsername,noticePassword,noticePwd;

    // Fragment管理对象
    private FragmentManager manager;
    private FragmentTransaction ft;
    private boolean booleanRight=false;

    private PersonalNomalInfo vo;

    //請求參數
    private Map<String, String> params;
    private HttpModel httpModel,registerHttpModel;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        activity = this.getActivity();
        manager = getFragmentManager();

        if (mView == null) {

            mView = inflater.inflate(R.layout.fragment_setpassword, container, false);


            initView();
            initListener();
            initRequest();
        }
        return mView;
    }

    private void initView() {

        txtTitle =  (TextView)mView.findViewById(R.id.txt_title);
        txtTitle.setText("設定登入賬號/密碼");
        imgBack =  (ImageView) mView.findViewById(R.id.img_back);

        if(LocalInfo.getUserInfo(activity)!=null){

            vo=LocalInfo.getUserInfo(activity);
            Log.e("getMobile===",vo.getMobile());
        }
        else{
            vo = new PersonalNomalInfo();
        }

    }

    private void initListener() {

        params = new HashMap<>();

        mView.findViewById(R.id.btn_pwd_next).setOnClickListener(this);
        etUsername = (EditText)mView.findViewById(R.id.et_username);
        etPassword = (EditText)mView.findViewById(R.id.et_password);
        etPwd = (EditText)mView.findViewById(R.id.et_pwd);
        uernameTv = (TextView) mView.findViewById(R.id.uername_tv);
        passwordTv = (TextView) mView.findViewById(R.id.password_tv);
        tvPwd  = (TextView) mView.findViewById(R.id.tv_pwd);
        noticeUsername = (TextView) mView.findViewById(R.id.notice_username);
        noticePassword = (TextView) mView.findViewById(R.id.notice_password);
        noticePwd = (TextView) mView.findViewById(R.id.notice_pwd);
        btn_pwd_next= (TextView) mView.findViewById(R.id.btn_pwd_next);

        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getFragmentManager().popBackStack();
            }
        });

        etUsername.addTextChangedListener(new TextWatcher() {


            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    uernameTv.setVisibility(View.VISIBLE);

                } else {
                    uernameTv.setVisibility(View.GONE);
                    int flag =0;
                    if(etUsername.length()<6){

                        flag=1;
                    }

                    if(!VilidateUtil.isAccount(String.valueOf(etUsername.getText()))){
                        flag=2;
                    }


                    if(flag>0){

                        if(flag==1){
                            noticeUsername.setVisibility(View.VISIBLE);
                            noticeUsername.setText("至少要6碼");
                        }
                        if(flag==2){
                            noticeUsername.setVisibility(View.VISIBLE);
                            noticeUsername.setText("只能用底線");
                        }
                        booleanRight=true;
                    }
                    else{
                        booleanRight=false;
                        noticeUsername.setVisibility(View.INVISIBLE);
                    }
                    if(!booleanRight){
                        Log.e("String.valueOf(etUser",String.valueOf(etUsername.getText()));
                        params.put("userName",String.valueOf(etUsername.getText()));
                        httpModel.startRequest();
                    }


                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etPassword.addTextChangedListener(new TextWatcher() {


            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    passwordTv.setVisibility(View.VISIBLE);
                } else {
                    int flag=0;
                    passwordTv.setVisibility(View.GONE);
                    if(etPassword.length()<6){
                        flag=1;
                    }

                    if(!VilidateUtil.isPwd(String.valueOf(etPassword.getText()))){

                        flag=2;
                    }

                    if(flag>0){

                        if(flag==1){
                            noticePassword.setVisibility(View.VISIBLE);
                            noticePassword.setText("至少要6碼");
                        }
                        if(flag==2){
                            noticePassword.setVisibility(View.VISIBLE);
                            noticePassword.setText("字母+數字");
                        }
                        booleanRight=true;
                    }
                    else{
                        booleanRight=false;
                        noticePassword.setVisibility(View.INVISIBLE);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        etPwd.addTextChangedListener(new TextWatcher() {


            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    tvPwd.setVisibility(View.VISIBLE);
                } else {
                    tvPwd.setVisibility(View.GONE);
                    int flag=0;
                    if(etPwd.length()<6){

                        flag=1;
                    }

                    if(!String.valueOf(etPwd.getText()).equals(String.valueOf(etPassword.getText()))){

                        flag=2;

                    }

                    if(flag>0){

                        if(flag==1){
                            noticePwd.setVisibility(View.VISIBLE);
                            noticePwd.setText("至少要6碼");
                        }
                        if(flag==2){
                            noticePwd.setVisibility(View.VISIBLE);
                            noticePwd.setText("密碼不一樣");
                        }
                        booleanRight=true;
                    }
                    else{
                        booleanRight=false;
                        noticePwd.setVisibility(View.INVISIBLE);
                    }

                }
                if(!booleanRight){
                    btn_pwd_next.setBackgroundResource(R.drawable.btn_red_shape);

                    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(etPwd.getWindowToken(), 0) ;

                    //保存數據

                    vo.setUserName(String.valueOf(etUsername.getText()));
                    Log.e("etUsernameetUsername",String.valueOf(etUsername.getText()));
                    vo.setPassword(String.valueOf(etPassword.getText()));
                    LocalInfo.saveUserInfo(activity,vo);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });



    }

    public void initRequest(){

        httpModel = new HttpModel(RequestUrl.baseUrl+RequestUrl.vilidateAccountUrl,params, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {

                if(VilidateUtil.isSuccess(resultCode)){
                    Map<String,String> result = (HashMap)data;

                    if (Double.parseDouble(String.valueOf(result.get("isSignUp")))==1) {
                        booleanRight=true;
                        noticeUsername.setVisibility(View.VISIBLE);
                        noticeUsername.setText("賬號已被使用");
                    }
                    else{
                        booleanRight=false;

                    }
                }
                else{
                    Toast.makeText(activity, "注冊失敗，請檢查網絡是否正常", Toast.LENGTH_SHORT).show();
                }

                Log.e("booleanRight===",""+booleanRight);
            }
        },true);

        //註冊請求
        registerHttpModel = new HttpModel(RequestUrl.baseUrl + RequestUrl.registerUrl, params, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {

                if (!VilidateUtil.isSuccess(resultCode)) {

                    MyAlertDialog dialog = new MyAlertDialog(activity, resultMsg, "");
                    dialog.show(activity, resultMsg, 0);


                } else {

                    Toast.makeText(activity, "注册成功", Toast.LENGTH_SHORT).show();

                    PersonalDataFragment register = new PersonalDataFragment();
                    ft = manager.beginTransaction();
                    //当前的fragment会被RegisterFragment替换
                    ft.replace(R.id.fragment_container, register);
                    ft.addToBackStack(null);
                    ft.commit();

                }
            }
        }, true);

    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_pwd_next:



                boolean isread = btn_pwd_next.getBackground().getCurrent().getConstantState().equals(getResources().getDrawable(R.drawable.btn_red_shape).getCurrent().getConstantState());

                if (isread) {
                //    btn_pwd_next.setBackgroundResource(R.drawable.btn_red_shape);

                    params.put("name", String.valueOf(etUsername.getText()));
                    params.put("userName", "test");
                    Log.e("vo.getName()===", "" + vo.getName() + ":::" + vo.getMobile());
                    params.put("birthday", "1900-01-01");
                    params.put("password", String.valueOf(etPwd.getText()));
                    params.put("mobile", vo.getMobile());
                    params.put("gender", "1");
               //     registerHttpModel.startRequest();
                    vo.setName(String.valueOf(etUsername.getText()));
                    vo.setPassword(String.valueOf(etPwd.getText()));
                    LocalInfo.saveUserInfo(activity,vo);
                    PersonalDataFragment register = new PersonalDataFragment();
                    ft = manager.beginTransaction();
                    //当前的fragment会被RegisterFragment替换
                    ft.replace(R.id.fragment_container, register);
                    ft.addToBackStack(null);
                    ft.commit();

                }
                else{
                 //   btn_pwd_next.setBackgroundResource(R.drawable.btn_grey_shape);
                }
                break;

        }




    }
}
